<template>
  <div class="w-1/3 mx-auto mt-40 shadow-2xl shadow-blue-300 rounded-box">
    <div class="avatar flex justify-center pt-4">
      <div class="w-24 rounded-full">
        <label for="avatar-input" class="cursor-pointer">
          <img :src="currentAvatarUrl" />
        </label>
      </div>
    </div>

    <input
      class="hidden"
      id="avatar-input"
      type="file"
      accept="image/*"
      @change="handleAvatarChange"
    />

    <div class="w-3/4 mx-auto">
      <label class="input input-bordered flex items-center gap-2 my-4">
        Name
        <input
          type="text"
          class="grow"
          value="Class 1 | Year 8"
          v-model="name"
        />
      </label>

      <select class="select select-bordered w-full mb-4" v-model="gender">
        <option disabled selected>Choose Gender</option>
        <option>male</option>
        <option>female</option>
      </select>
    </div>

    <div class="text-center">
      <button class="btn btn-primary my-2" @click="onClick">
        Update Profile
      </button>
    </div>
  </div>
</template>

<script setup>
import { uploadAvatar } from '@/services/apiStorage';
import { getStudentByStudentId, updateStudent } from '@/services/apiStudent';
import { getConfig } from '@/utils/configHelper';
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { useRoute } from 'vue-router';

const route = useRoute();
const router = useRouter();

const name = ref('someone');
const gender = ref('male');

const currentAvatarUrl = ref(
  'https://img.daisyui.com/images/stock/photo-1534528741775-53994a69daeb.webp'
);
const avatarFile = ref(null);

function handleAvatarChange(event) {
  const file = event.target.files[0];
  avatarFile.value = file;

  const newAvatarUrl = URL.createObjectURL(file);
  currentAvatarUrl.value = newAvatarUrl;
}

async function onClick() {
  const newStudent = {
    name: name.value,
    gender: gender.value,
  };

  if (avatarFile.value) {
    // Build avatar filename
    const token = getConfig('SUPABASE_TOKEN');
    const supabaseURL = getConfig('SUPABASE_URL');

    const userToken = JSON.parse(localStorage.getItem(token));
    const newAvatarFilename = `${userToken.user.email}-${Date.now()}.png`;

    // Upload avatar file
    await uploadAvatar(avatarFile.value, newAvatarFilename);

    // Update student info in supabase
    const avatar = `${supabaseURL}/storage/v1/object/public/avatar/public/${newAvatarFilename}`;

    newStudent.avatar = avatar;
  }

  const student = await updateStudent(route.params.id, newStudent);
  console.log(student);

  router.push({ name: 'student' });
}

onMounted(async () => {
  const studentId = route.params.id;

  const student = await getStudentByStudentId(studentId);

  name.value = student.name;
  gender.value = student.gender;
  currentAvatarUrl.value = student.avatar;
});
</script>
